package info.thereisonlywe.onenesspathfinder.configuration;

import info.thereisonlywe.core.data.DataHolder;
import info.thereisonlywe.core.io.FileIO;
import info.thereisonlywe.core.toolkit.StringToolkit;

import java.io.File;

/**
 * @author thereisonlywe
 */

public class StartupSettings extends DataHolder {

	public static final File STARTUP_SETTINGS_FILE = new File("userdata"
			+ File.separator + "StartupSettings");

	private final String fields[] = { "language" };

	public boolean loaded = false;

	@SuppressWarnings("unused")
	private StartupSettings()
	{
	}

	public StartupSettings(boolean load) // true for get
	{
		if (load)
		{
			final String readsettings = FileIO
					.readString(STARTUP_SETTINGS_FILE);
			if (readsettings != null && !readsettings.isEmpty())
			{
				load(readsettings);
				loaded = true;
			}
		}
	}

	public StartupSettings(final String savedsettings)
	{
		load(savedsettings);
		loaded = true;
	}

	private void load(final String savedsettings)
	{
		synchronized (super.map)
		{
			for (String s : StringToolkit.splitLines(savedsettings))
			{
				if (!(s.isEmpty() || !s.contains("=")))
				{
					final String[] statement = StringToolkit.splitStatement(s,
							'=');
					super.map.put(statement[0], statement[1]);
				}
			}
		}
	}

	/**
	 * Writes settings
	 * 
	 * @param name
	 */
	public void write()
	{
		StringBuilder sb = new StringBuilder();
		String s;
		for (int i = 0; i < fields.length; i++)
		{
			s = fields[i] + "=" + get(fields[i]);
			sb.append(s);
			if (i + 1 < fields.length) sb.append("\n");
		}

		FileIO.write(sb.toString(), STARTUP_SETTINGS_FILE, false);
		sb = null;
		s = null;
	}
}
